//
//  HomeViewController.swift
//  StoryDemo
//
//  Created by mac on 2019/6/28.
//  Copyright © 2019年 zhkj. All rights reserved.
//

import UIKit
import MJRefresh
import Alamofire

class HomeViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,WRCycleScrollViewDelegate,PYSearchViewControllerDelegate {
    
    var pageNo:Int = 1
    let pageSize:Int = 10
    var loadDataSuccess:Bool = false
    var productList = [HomeProduct]()
    var limitList=[Lists]()
    
    @IBOutlet weak var searchView: UIView!
    @IBOutlet weak var codeView: UIImageView!
    @IBOutlet weak var msgView: UIImageView!
    
    var cycleScrollView:WRCycleScrollView?
    var limitBuyTableView:UITableView=UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        searchView.layer.cornerRadius=5
        searchView.addOnClickListener(target: self, action: #selector(search))
        
        initTable()
        //        loadbanner()
        loadlimit()
        loadData()
    }
    @objc func search(){
        let hotSeaches = ["冰箱", "空调", "佰益莱", "航天", "防盗门","垃圾处理器", "一能净", "热水器", "电视"]
        let searchViewController: PreSearchViewController = PreSearchViewController.init(hotSearches: hotSeaches, searchBarPlaceholder: Bundle.py_localizedString(forKey: PYSearchSearchPlaceholderText)) { [weak self] (searchViewController, searchBar, searchText) in
            guard let strongSelf = self else { return }

            let resultsViewController = ResultsViewController(keywords: searchText!, cid: "")
            strongSelf.navigationController?.pushViewController(resultsViewController, animated: false)
        }

        searchViewController.hotSearchStyle = .default
        searchViewController.searchHistoryStyle = .normalTag
        searchViewController.swapHotSeachWithSearchHistory = true
        searchViewController.delegate = self

//        searchViewController.searchViewControllerShowMode = .modeModal
        searchViewController.searchViewControllerShowMode = .modePush
//        searchViewController.hidesBottomBarWhenPushed = true

//        self.navigationController?.setNavigationBarHidden(false, animated: true)

//        searchViewController.backButton.setTitle("", for: .normal)
        self.navigationController?.pushViewController(searchViewController, animated: true)
        searchViewController.navigationController?.setNavigationBarHidden(false, animated: false)
    }
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    func searchViewController(_ searchViewController: PYSearchViewController!, searchTextDidChange searchBar: UISearchBar!, searchText: String!) {
        if searchText.count > 0 {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                var searchSuggestionsM = [String]()
                for i in 0..<(1 + arc4random() % 10) {
                    searchSuggestionsM.append(String(format: "Search suggestion %ld", i))
                }
                searchViewController.searchSuggestions = searchSuggestionsM
            }
        }
    }
    func initTable(){
        limitBuyTableView=UITableView(frame: CGRect(x: 0, y: 100, width: screenW, height: screenH-100),style:.grouped)
        
        limitBuyTableView.rowHeight = UITableView.automaticDimension
        limitBuyTableView.estimatedRowHeight = 900
        limitBuyTableView.dataSource=self
        limitBuyTableView.delegate=self
        limitBuyTableView.separatorInset=UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        limitBuyTableView.contentInset=UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        limitBuyTableView.register(UINib (nibName: "TwoLabelTableViewCell", bundle: nil), forCellReuseIdentifier: "re")
        limitBuyTableView.register(UINib (nibName: "HomeHeaderCell", bundle: nil), forCellReuseIdentifier: "cell")
        
        //refresh
        let header = TTRefreshHeader.init(refreshingBlock: {[weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = 1
            strongSelf.limitBuyTableView.mj_footer.state = .idle
            strongSelf.limitBuyTableView.mj_header.endRefreshing()
            strongSelf.loadlimit()
            strongSelf.loadData()
            strongSelf.loadbanner()
        })
        
        limitBuyTableView.mj_header = header;
        
        let footer = TTRefreshFooter  {  [weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = strongSelf.pageNo + 1
            strongSelf.loadData();
        }
        
        limitBuyTableView.mj_footer = footer
        limitBuyTableView.mj_footer.isHidden = true
        
        self.view.addSubview(limitBuyTableView)
    }
    
    func initBanner(serverImages:[String]){
        
        let height = screenW / 2.6
        let frame = CGRect(x: 0, y: 0, width: screenW, height: height)
        // 可加载网络图片或者本地图片
        //        let serverImages = ["http://p.lrlz.com/data/upload/mobile/special/s252/s252_05471521705899113.png",              "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007678060723.png",                  "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007587372591.png",                    "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007388249407.png",                    "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007470310935.png"]
        // 构造方法
        cycleScrollView = WRCycleScrollView(frame: frame, type: .SERVER, imgs: serverImages)
        // 添加代理
        cycleScrollView?.delegate = self
    }
    func loadbanner(){
        
        AlamofireHelper.get(url: home_json, parameters: nil, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            let homeModule=mHomeModule.init(json: res)
            let lModules=homeModule.LModules
            var banners = [String]()
            for lmodule in lModules{
                if lmodule.type==9{
                    let dataset=lmodule.content?.dataset
                    for data in dataset!{
                        banners.append(data.pic!)
                    }
                }
            }
            ss.initBanner(serverImages: banners)
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.limitBuyTableView.mj_header.isRefreshing(){ss.limitBuyTableView.mj_header.endRefreshing()}
            else if ss.limitBuyTableView.mj_footer.isRefreshing() {ss.limitBuyTableView.mj_footer.endRefreshing()}
        }
    }
    
    func loadlimit(){
        var d = ["pageNo":"1",
                 "pageSize":String(pageSize),
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetlismitBuyList, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.loadDataSuccess = true
            let limitBuyResult=LimitBuyResult.init(json: res)
            ss.limitList=limitBuyResult.List
            ss.limitBuyTableView.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.loadDataSuccess = false
            if ss.limitBuyTableView.mj_header.isRefreshing(){ss.limitBuyTableView.mj_header.endRefreshing()}
            else if ss.limitBuyTableView.mj_footer.isRefreshing() {ss.limitBuyTableView.mj_footer.endRefreshing()}
        }
    }
    
    func loadData() {
        //HUD.show(withStatus: NSLocalizedString("Loading", comment: ""))
        var d = ["pageNo":String(pageNo),
                 "pageSize":String(pageSize),
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        
        AlamofireHelper.get(url: Get, parameters: d, successHandler: {[weak self] (res) in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.loadDataSuccess = true
            
            if ss.pageNo == 1{ ss.productList.removeAll()}
            
            if ss.limitBuyTableView.mj_header.isRefreshing(){
                ss.limitBuyTableView.mj_header.endRefreshing()
            }else if ss.limitBuyTableView.mj_footer.isRefreshing() {
                ss.limitBuyTableView.mj_footer.endRefreshing()
                
            }
            let homeResult=HomeResult.init(json: res)
            
            
            if homeResult.Product.count>0 {
                if ss.limitBuyTableView.mj_footer.isHidden && homeResult.Product.count > 0 {
                    ss.limitBuyTableView.mj_footer.isHidden = false
                }
                ss.productList.insert(contentsOf: homeResult.Product, at: ss.productList.count)
                if ss.productList.count < ss.pageSize {
                    ss.limitBuyTableView.mj_footer.state = .noMoreData
                }
            }else {
                ss.limitBuyTableView.mj_footer.state = .noMoreData
            }
            
            ss.limitBuyTableView.reloadData()
            //print(res);
        }) {[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.loadDataSuccess = false
            if ss.limitBuyTableView.mj_header.isRefreshing(){ss.limitBuyTableView.mj_header.endRefreshing()}
            else if ss.limitBuyTableView.mj_footer.isRefreshing() {ss.limitBuyTableView.mj_footer.endRefreshing()}
        }
    }
    
    /// 点击图片事件
    func cycleScrollViewDidSelect(at index:Int, cycleScrollView:WRCycleScrollView)
    {
        //        print("点击了第\(index+1)个图片")
    }
    
    /// 图片滚动事件
    func cycleScrollViewDidScroll(to index:Int, cycleScrollView:WRCycleScrollView)
    {
        //        print("滚动到了第\(index+1)个图片")
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section==0 ? screenW/2.6 : 70
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 0:
            loadbanner()
            return cycleScrollView
        case 1:
            let img1 = UIImageView(frame: CGRect(x: 0, y: 0, width: screenW, height: 70))
            img1.image=UIImage(named: "home_banner2")
            img1.addOnClickListener(target: self, action: #selector(zhsf))
            return img1
        default:
            let img2 = UIImageView(frame: CGRect(x: 0, y: 0, width: screenW, height: 70))
            img2.image=UIImage(named: "renqi")
            return img2
        }
    }
    func checkLogin() {
        if userkey==nil{
            self.navigationController?.pushViewController(LoginViewController(), animated: true)
            return
        }
    }
    @objc func zhsf(){
        checkLogin()
        self.navigationController?.pushViewController(SendOrderViewController(), animated: true)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return limitList.count
        default:
            return productList.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell=tableView.dequeueReusableCell(withIdentifier: "cell")
            cell?.selectionStyle = .none
            return cell!
        case 1:
            let cell=tableView.dequeueReusableCell(withIdentifier: "re") as!TwoLabelTableViewCell
            let product=limitList[indexPath.row]
            
            if let url = URL.init(string: product.ProductImg!){
                cell.icon.setImage(path: url)
            }
            var str=""
            for index in 0..<(product.ProductAttributeInfos.count>3 ? 3 : product.ProductAttributeInfos.count){
                str+=product.ProductAttributeInfos[index]+"|"
            }
            cell.label.text=str.count>0 ? str.prefix(str.count-1).description : ""
            
            cell.name.text=product.ProductName!
            cell.price.text="￥\(product.MinPrice)"
            let priceString = NSMutableAttributedString.init(string: "￥\(product.MarketPrice)")
            priceString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSNumber.init(value: 1), range: NSRange(location: 0, length: priceString.length))
            cell.oldPrice.attributedText=priceString
            cell.selectionStyle = .none
            cell.gobuy.setTitle("去抢购", for: .normal)
            if product.ShopName=="官方自营店"{
                cell.name.text="           \(product.ProductName!)"
                cell.pre_label.isHidden=false
                cell.pre_label.text="官方"
                cell.pre_label.backgroundColor=UIColor.red
                cell.pre_label.textColor=UIColor.white
                cell.pre_label.font=UIFont.systemFont(ofSize: 12)
                cell.pre_label.paddingLeft=5
                cell.pre_label.paddingRight=5
                cell.pre_label.layer.cornerRadius=5
                cell.pre_label.clipsToBounds=true
            }else{
                cell.name.text=product.ProductName
                cell.pre_label.isHidden=true
            }
            
            
            return cell
        default:
            let cell=tableView.dequeueReusableCell(withIdentifier: "re") as!TwoLabelTableViewCell
            let product=productList[indexPath.row]
            
            let url = URL.init(string: product.ImageUrl!)!
            cell.icon.setImage(path: url)
            
            var str=""
            for index in 0..<(product.ProductAttributeInfos.count>3 ? 3 : product.ProductAttributeInfos.count){
                str+=product.ProductAttributeInfos[index]+"|"
            }
            cell.label.text=str.count>0 ? str.prefix(str.count-1).description : ""
            cell.name.text=product.Name
            cell.price.text="￥"+product.SalePrice!
            let priceString = NSMutableAttributedString.init(string: "￥\(product.MarketPrice!)")
            priceString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSNumber.init(value: 1), range: NSRange(location: 0, length: priceString.length))
            cell.oldPrice.attributedText=priceString
            cell.gobuy.setTitle("去购买", for: .normal)
            cell.selectionStyle = .none
            if product.ShopName=="官方自营店"{
                cell.name.text="           \(product.Name!)"
                cell.pre_label.isHidden=false
                cell.pre_label.text="官方"
                cell.pre_label.backgroundColor=UIColor.red
                cell.pre_label.textColor=UIColor.white
                cell.pre_label.font=UIFont.systemFont(ofSize: 12)
                cell.pre_label.paddingLeft=5
                cell.pre_label.paddingRight=5
                cell.pre_label.layer.cornerRadius=5
                cell.pre_label.clipsToBounds=true
            }else{
                cell.name.text=product.Name
                cell.pre_label.isHidden=true
            }
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        switch indexPath.section {
        case 1:
            let pid = String(limitList[indexPath.row].ProductId)
            self.navigationController?.pushViewController(ProductDetailViewController(pid: pid), animated: true)
        case 2:
            let pid = productList[indexPath.row].Id
            self.navigationController?.pushViewController(ProductDetailViewController(pid: pid!), animated: true)
        default: break
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
